package top.lyc829.aircontroller.logic.network

import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import top.lyc829.aircontroller.MyApp
import top.lyc829.aircontroller.logic.utils.GlobalConfig.COMMON_ADDRESS


object HttpUtil {

    private const val BASE_URL = "http://192.168.240.153:5000"

    fun getHttp(address: String, callback: okhttp3.Callback) {
        val client = OkHttpClient()
        val auth = MyApp.sp.getSP("auth") ?: ""
        val request = Request.Builder()
                .url(BASE_URL + address)
                .addHeader("auth", auth)
                .build()
        client.newCall(request).enqueue(callback)
    }

    fun postHttp(address: String, body: Map<String, String>, callback: okhttp3.Callback) {
        val client = OkHttpClient()
        val JSON: MediaType? = "application/json; charset=utf-8".toMediaTypeOrNull()
        val gson = Gson()
        val param: String = gson.toJson(body)

        val requestBody: RequestBody = param.toRequestBody(JSON)
        val auth = MyApp.sp.getSP("auth") ?: ""
        val request = Request.Builder()
                .post(requestBody)
                .addHeader("auth", auth)
                .url(BASE_URL + address)
                .build()

        client.newCall(request).enqueue(callback)
    }

}